import React, { useState } from 'react'
import './style.css'

const Loading = () => (
    <div className="loading-overlay">
        <div className="loading-spinner"></div>
    </div>
)

let loadingCount = 0
let setLoading: React.Dispatch<React.SetStateAction<boolean>> | null = null

export const LoadingProvider = ({ children }: { children: React.ReactNode }) => {
    const [isLoading, setIsLoading] = useState(false)
    setLoading = setIsLoading

    return (
        <>
            {isLoading && <Loading />}
            {children}
        </>
    )
}

export const showLoading = () => {
    loadingCount++
    if (setLoading && loadingCount === 1) {
        setLoading(true)
    }
}

export const hideLoading = () => {
    loadingCount = Math.max(0, loadingCount - 1)
    if (setLoading && loadingCount === 0) {
        setLoading(false)
    }
}